package com.ht.util.ssh;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.util.io.input.NoCloseInputStream;
import org.apache.sshd.common.util.io.output.NoCloseOutputStream;


public class SshUtils {

    /**
     *
     * 执行命令
     * @param conn：连接信息
     * @param cmd：执行命令
     * @param timeout：执行时间
     * @return
     * @throws IOException
     */
    public static SshResponse runCommand(SshConnection conn, String cmd, long timeout) throws IOException {
        SshClient client = SshClient.setUpDefaultClient();
        try {
            client.start();
            ConnectFuture cf = client.connect(conn.getUsername(), conn.getIp(), 22);

            ClientSession session = cf.verify().getSession();
            session.addPasswordIdentity(conn.getPassword());
            session.auth().verify(TimeUnit.SECONDS.toMillis(timeout));

            ChannelExec ce = session.createExecChannel(cmd);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayOutputStream err = new ByteArrayOutputStream();
            ce.setOut(out);
            ce.setErr(err);

            ce.open();
            Set<ClientChannelEvent> events = ce.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
            session.close(false);

            return new SshResponse(out.toString(), err.toString(), ce.getExitStatus());

        } finally {
            client.stop();
        }

    }


    public static void main(String[] args) throws Exception {
        SshConnection conn = new SshConnection().setIp("192.168.3.70").setPort(22).setUsername("root").setPassword("123qwe...");
        String cmd = "libreoffice7.6 --convert-to pdf:writer_pdf_Export /home/minio/data/htfile/1719214628683_测试.docx --outdir /home/minio/data/htfile";
        SshResponse response = runCommand(conn, cmd, 15);

        if(response.getReturnCode()==0){
            //执行成功
            System.out.println("stdOutput=>"+response.getStdOutput());
        }else{
            //执行失败
            System.out.println("errOutput=>"+response.getErrOutput());
        }

    }
}

